﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace TaskDemo
{
    public class Demo2
    {
        public async void CancelTaskDemo1()
        {
            // 第一个参数，意思是三秒之后就取消这个任务
            var cts = new CancellationTokenSource(3000);
            // cts.CancelAfter(3000); // 也是三秒钟之后取消任务
            var token = cts.Token;

            var sw = Stopwatch.StartNew();
            try
            {
                var cancelTask = Task.Run(async () =>
                {
                    await Task.Delay(3000);
                    cts.Cancel();
                });

                await Task.WhenAll(Task.Delay(5000, token), cancelTask);
            }
            catch (TaskCanceledException e)
            {
                Console.WriteLine(e);
            }
            finally
            {
                cts.Dispose();
            }
            Console.WriteLine($"Task complete in{sw.ElapsedMilliseconds}ms");
        }

        // cancellationToken 使用介绍 重载
        async Task FooAsync(CancellationToken cancellationToken)
        {
            await Task.Delay(5000);
            Console.WriteLine("do somthing");
            var client = new HttpClient();
            await client.GetStringAsync("123123", cancellationToken);
        }

        async Task FooAsync()
        {
            FooAsync(CancellationToken.None);
        }

        async Task FooAsync(int delay,CancellationToken? cancellationToken = null)
        {
            var token = cancellationToken ?? CancellationToken.None;
            await Task.Delay(delay, token);
        }

        Task FooAsync2(CancellationToken cancellationToken)
        {
            return Task.Run(async () =>
            {
                if (cancellationToken.IsCancellationRequested)
                    cancellationToken.ThrowIfCancellationRequested();
                while (true) {
                    if (cancellationToken.IsCancellationRequested)
                        cancellationToken.ThrowIfCancellationRequested();
                    Thread.Sleep(1000);
                    Console.WriteLine("Pooling...");
                }

                var outputs = new int[1000];
                for (int i = 0; i < 1000; i++)
                {
                    if (cancellationToken.IsCancellationRequested)
                        cancellationToken.ThrowIfCancellationRequested();
                    outputs[i] = i * i;
                }

                await Task.Delay(1000, cancellationToken);

                File.ReadAllText("123123");
                File.ReadAllTextAsync("123123", cancellationToken);
            });
        }
    }
}
